package com.xzhuang.task.web;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xzhuang.task.util.QuartzUtil;

public class SecurityFilter extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// System.out.println("==>>Begin to Filter session====");
		String[] extName = { "jpg", "js", "css", "png", "gif" };
		List fiterList = new ArrayList();
		fiterList.add("http://localhost:8080/task/login");
		HttpSession session = request.getSession();
		String user = (String) session.getAttribute(QuartzUtil.USERINFO);
		// System.out.println("===??Current User==" + user);
		String curPath = request.getRequestURL().toString();

		// if (curPath.indexOf("GPS/User/Index") >= 0) { return true; }
		String bl = getUrlLastExtName(curPath);
		if (!fiterList.contains(curPath)) {
			if (!Arrays.asList(extName).contains(bl)) {
				if (null == user) {
					// 未登录
					response.setCharacterEncoding("UTF-8");
					response.setContentType("text/html;charset=UTF-8");
					PrintWriter out = response.getWriter();

					StringBuilder builder = new StringBuilder();
					builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
					builder.append("alert(\"页面过期，请先登录!\");");
					builder.append("window.location.href=\"login.jsp\";");
					builder.append("</script>");
					// builder.append(Constants.basePath);
					// builder.append("/background/index.html\";</script>");
					out.print(builder.toString());
					out.close();
					return false;
				}
			}
		}

		return super.preHandle(request, response, handler);
	}

	public String getUrlLastExtName(String url) {
		if (url != null && url.length() > 0) {
			if (url.indexOf(".") != -1) {
				return url.substring(url.lastIndexOf(".") + 1, url.length());
			}
		} else {
			return url;
		}
		return null;
	}
}